package net.lab1024.sa.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.gateway.util.TrafficUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 设备指纹过滤器：生成客户端唯一标识，用于防刷和风控追踪
 * 核心逻辑：基于IP+UA+浏览器信息+动态盐值生成唯一指纹
 */
@Slf4j
@Component
@Order(-2) // 优先于限流过滤器执行
public class DeviceFingerprintFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 生成设备指纹（IP+UA+Accept-Language+盐值）
        String fingerprint = TrafficUtils.generateDeviceFingerprint(exchange);
        // 存入请求头和exchange属性（供后续处理器使用）
        exchange.getRequest().mutate().header("X-Device-Fingerprint", fingerprint).build();
        exchange.getAttributes().put("DEVICE_FINGERPRINT", fingerprint);
        return chain.filter(exchange);
    }

}